package com.wallellen.android.currencies;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Iterator;

public class SplashActivity extends Activity {
    public static final String URL = "http://openexchangerates.org/api/currencies.json";
    public static final String KEY_ARRAYLIST = "key_arraylist";
    private ArrayList<String> mCurrencies;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_splash);

        new FetchCodesTask().execute(URL);
    }

    private class FetchCodesTask extends AsyncTask<String, Void, JSONObject> {
        @Override
        protected JSONObject doInBackground(String... params) {
            return new JSONParser().getJSONFromUrl(params[0]);
        }

        @Override
        protected void onPostExecute(JSONObject jsonObject) {
            //super.onPostExecute(jsonObject);

            try {
                if (jsonObject == null) {
                    throw new JSONException("Invalid");
                }

                Iterator<String> iterator = jsonObject.keys();
                String key;
                mCurrencies = new ArrayList<>();
                while (iterator.hasNext()) {
                    key = iterator.next();
                    mCurrencies.add(key + " | " + jsonObject.getString(key));
                }

                Intent intent = new Intent(SplashActivity.this, MainActivity.class);
                intent.putExtra(KEY_ARRAYLIST, mCurrencies);
                startActivity(intent);
            } catch (JSONException ex) {
                Toast.makeText(SplashActivity.this, "There's been a JSON Exception: " + ex, Toast.LENGTH_LONG).show();
                Log.e(SplashActivity.class.getName(), ex.getMessage(), ex);
            } finally {
                finish();
            }
        }
    }

}
